package com.example.areaofthesquare;

import java.util.ArrayList;
import java.util.List;

public class Operation {

    public static final int INF = 0x3f3f3f3f;
    public static final double EPS = 1e-12;
    private float maxX;
    private float minX;
    private float maxY;
    private float minY;
    private float bian;
    private float anglea;

    private List<Point> mPointList;

    public Operation(List<Point> mPointList) {
        this.mPointList = mPointList;
    }

    /*计算正方形的面积*/
    public double getArea() {
        float low = 0;
        float high = (float) (Math.PI / 2.0);
        float mid1;
        float mid2;
        while(low+EPS < high){
            mid1 = (float) ((low+high) / 2.0);
            mid2 = (float) ((mid1+high) / 2.0);
            if(getSide(mid1) > getSide(mid2)){
                low = mid1;
            }else{
                high = mid2;
            }
        }
        anglea = (float) low;
        bian = getSide(anglea);

        return bian*bian;

    }

    /*获得最长的边长*/
    public float getSide(float angle) {
         minX = INF;
         maxX = -INF;
         minY = INF;
         maxY = -INF;
        double x;
        double y;
        for (int i = 0; i < mPointList.size(); i++) {
            x = mPointList.get(i).getX() * Math.cos(angle) - mPointList.get(i).getY() * Math.sin(angle);
            y = mPointList.get(i).getY() * Math.cos(angle) + mPointList.get(i).getX() * Math.sin(angle);
            maxX = (float) Math.max(maxX, x);
            minX = (float) Math.min(minX, x);
            maxY = (float) Math.max(maxY, y);
            minY = (float) Math.min(minY, y);
        }
        return Math.max(maxX - minX, maxY - minY);
    }

    public List<Point> getFourPoint(){
        Point point1 = new Point(minX,minY);
        Point point2 = new Point(minX,minY+bian);
        Point point3 = new Point(minX+bian,minY+bian);
        Point point4 = new Point(minX+bian,minY);
        List<Point> fourPointList = new ArrayList<>();
        fourPointList.add(point1);
        fourPointList.add(point2);
        fourPointList.add(point3);
        fourPointList.add(point4);

//        for (int i = 0; i < fourPointList.size(); i++) {
//            float x = (float) (fourPointList.get(i).getX() * Math.cos(anglea) - fourPointList.get(i).getY() * Math.sin(anglea));
//            float y = (float) (fourPointList.get(i).getY() * Math.cos(anglea) + fourPointList.get(i).getX() * Math.sin(anglea));
//
//            fourPointList.get(i).setX(x);
//            fourPointList.get(i).setY(y);
//        }
        return fourPointList;
    }

}

